<template>
    <div class="userInfo">
        <el-form ref="AddCarRef" :rules="rules" style="max-width: 600px" :model="userInfo" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userInfo.username" placeholder="请输入用户名" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userInfo.password" placeholder="请输入密码" />
                    </el-form-item>
                    <el-form-item label="身份证号" prop="identity">
                        <el-input v-model="userInfo.identity" placeholder="请输入身份证号" />
                    </el-form-item>
                    <el-form-item label="姓名" prop="realName">
                        <el-input v-model="userInfo.realName" placeholder="请输入姓名" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="userInfo.sex" placeholder="请选择性别">
                            <el-option :value="0">男</el-option>
                            <el-option :value="1">女</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="图片">
                        <div class="image-container">
                            <el-upload
                                :action="baseURL + '/upload'"
                                :show-file-list="false"
                                :on-success="handleSuccess"
                                :on-change="beforeAvatarUpload"
                                class="upload-placeholder"
                            >
                            <img v-if="imageUrl" :src="imageUrl" alt="项目图片" class="uploaded-image square-image">
                            <el-icon v-else><Plus /></el-icon>
                            </el-upload>
                        </div>
                    </el-form-item>
                    <el-form-item label="活跃状态" prop="available">
                        <el-select v-model="userInfo.available" placeholder="请选择活跃状态">
                            <el-option :value="0">禁用</el-option>
                            <el-option :value="1">活跃</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input type="textarea" v-model="userInfo.address" :rows="3" placeholder="请输入地址" />
                    </el-form-item>
                    <el-form-item style="display: flex; justify-content: center;" >
                        <el-button type="primary" @click="submitForm(AddCarRef)">保存</el-button>
                        <el-button @click="resetForm(AddCarRef)">重置</el-button>
                    </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules,} from 'element-plus'
import { addUser, getUserById, updateUser } from '@/api'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useRoute } from 'vue-router';

const formSize = ref<ComponentSize>('default')
const AddCarRef = ref<FormInstance>()
let userInfo = reactive({
    id: '',
    username: '',
    password: '',
    identity: '',
    realName: '',
    sex: '',
    address: '',
    type: '1',
    available: '',
    img: ''
})

const id = ref()

// 在组件挂载时初始化数据
onMounted(() => {
    const route = useRoute();
    // 获取查询参数 id存在则是编辑 反之新增
    id.value = route.query.id as string | undefined;
    if(id.value){
        // 发送请求 根据id查数据
        getUserById(id.value).then((resp: { data: any; }) => {
            let data = resp.data;
            if (data.code == '50041') {
                Object.assign(userInfo, data.data);
            } else {
                ElMessage({
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }
});

const baseURL = ref('http://localhost:8081/common')
const imageUrl = ref('') // 用来存储图片URL
const handleSuccess = (response : any, uploadFile: any) => {
    // 假设API响应中包含图片URL，这里需要根据实际API返回结构调整
    imageUrl.value = baseURL.value +`/download?name=${response.data}`;
    userInfo.img = response.data
}

const beforeAvatarUpload = (file : any) => {
    const suffix = file.name.split('.')[1]
    const size = file.size / 1024 / 1024 < 10
    if(['png','jpeg','jpg'].indexOf(suffix) < 0){
        ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！')
        return false
    }
    if(!size){
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
    }
    return true
}


const rules = reactive<FormRules>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    identity: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    available: [{ required: true, message: '请选择活跃状态', trigger: 'change' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(id.value){
                updateUser(userInfo).then((resp: { data: any; }) => {
                    let data = resp.data;
                    if (data.code == '50031') {
                        ElMessage({
                            message: data.message,
                            type: 'success'
                        });
                        // 发送消息给父窗口，告知要改变页面
                        window.parent.postMessage({ action: 'changePage', url: '/#/user/list' }, '*');
                    } else {
                        ElMessage({
                            message: data.message,
                            type: 'error'
                        });
                    }
                });
            }else{
                addUser(userInfo).then((resp: { data: any; }) => {
                    let data = resp.data;
                    if (data.code == '50011') {
                        ElMessage({
                            message: data.message,
                            type: 'success'
                        });
                        // 发送消息给父窗口，告知要改变页面
                        window.parent.postMessage({ action: 'changePage', url: '/#/user/list' }, '*');
                    } else {
                        ElMessage({
                            message: data.message,
                            type: 'error'
                        });
                    }
                });
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>
<style scoped>
.userInfo {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    padding: 20px;
    box-sizing: border-box;
}
/* 为上传区域添加样式 */
.upload-placeholder {
  position: relative;
  width: 150px; /* 自定义宽度，根据需求调整 */
  height: 150px; /* 自定义高度，应与宽度相同以形成正方形 */
  border: 1px solid #000; /* 黑色边框 */
  border-radius: 4px; /* 边框圆角，保持直角以维持方形外观 */
  overflow: hidden; /* 隐藏超出边界的图片部分 */
  display: flex; /* 添加Flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.square-image {
    max-width: 100%;
    width: auto;
    max-height: 100%;
    height: auto;
    /* 保持图片原始宽高比 */
    object-fit: contain; /* 更改此属性为contain以保持原图比例 */
    /* 确保图片内容居中 */
    object-position: center;
    
    /* 居中显示 */
    display: block;
    margin: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    border-radius: 0 !important; /* 确保没有圆角 */
}

/* 当没有图片时，确保加号图标居中显示（这部分可能不需要额外设置，因为已经通过Flex布局居中） */
/*.upload-placeholder .el-icon {
  // 如果之前设置导致问题，可以尝试移除此部分，仅依赖Flex布局的居中效果
}*/

/* 可选：调整加号图标的样式 */
.el-icon {
  font-size: 48px; /* 根据需要调整图标大小 */
  color: #909399; /* 图标颜色，可根据设计调整 */
}
</style>